from sqlalchemy import Column, String, Integer, DateTime, func, Numeric, ForeignKey, Text
from sqlalchemy.orm import relationship, backref

from database import db
from .brand import Brand
from .category import ProductCategory
from .resource import Resource


# class ProductContent(database.Model):
#     language = CharField(db_column='language', max_length=10, null=False)
#     product_id = CharField(db_column='product_id', null=False)
#     summary = CharField(db_column='summary', max_length=400, help_text='产品摘要', null=True)
#     detail = TextField(db_column='detail', help_text='产品详情')
#
#     class Meta:
#         # db_table = '{0}_{1}'.format(TABLE_PREFIX, 'product_content')
#         primary_key = CompositeKey('language', 'product_id')

class Product(db.Model):
    STATUE_REMOVED = 'removed'
    __table_name__ = 'product'
    id = Column(String(200), primary_key=True)
    title = Column(String(400), nullable=False)
    sub_title = Column(String(400), nullable=False)
    status = Column(String(20), default='normal')
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now())
    like_count = Column(Integer, default=0)
    view_count = Column(Integer, default=0)
    mask = Column(String(32), nullable=True)
    structure = Column(String(80), nullable=True)
    minimum_price = Column(Numeric(precision=4), default=0.00)
    maximum_price = Column(Numeric(precision=4), default=0.00)
    stock = Column(Integer, default=0)
    # cover = Column(String(400))
    cover_resource_id = Column(ForeignKey(Resource.id))
    tags = Column(String(300), nullable=True)
    category_id = Column(ForeignKey(ProductCategory.id))
    category = relationship(ProductCategory)
    cover = relationship(Resource)
    average_price = Column(Numeric(precision=4), default=0.00)
    brand_id = Column(ForeignKey(Brand.id))
    brand = relationship(Brand)
    # gallery = relationship(Resource)

    gallery = relationship(Resource, secondary='product_gallery')
class ProductMetadata(db.Model):
    __table_name__ = 'product_metadata'
    id = Column(Integer(), primary_key=True)
    metadata_id = Column(String())
    name = Column(String())
    product_id = Column(ForeignKey(Product.id))
    value = Column(String(400))
    product = relationship(Product, backref=backref('extData'))


class ProductContent(db.Model):
    language_code = Column(String(40), primary_key=True)
    product_id = Column(ForeignKey(Product.id), primary_key=True)
    summary = Column(String(400))
    detail = Column(Text)
    product = relationship(Product
                           , backref=backref('contents'), lazy="joined")

class ProductGallery(db.Model):
    id = Column(Integer, primary_key=True, autoincrement=True)
    product_id = Column(ForeignKey(Product.id))
    resource_id = Column(ForeignKey(Resource.id))
